Programming III - Loops, conditionals, & OOP

GEOG 30323

September 15, 2016

Python refresher

  • Exercise available in SageMathCloud

Iteration

Iteration

  • At your jobs, you will often need to repeat the same task over and over!
  • From your textbook: “Repeating identical or similar tasks without making errors is something that computers do well and people do poorly.”
  • Solution: make the computer do it with iteration

Loops

  • Loops are operators that tell the computer to repeat an action a given number of times
  • Common loops:
    • for: Repeats an action over a series of items
    • while: Repeats an action until a given condition is satisfied
  • Important note: loops, like functions, must obey whitespace rules!

The for loop

  • for repeats an action for every element in an object
  • Example:
>>> for character in 'Kyle': 
...     print("Give me a " + character + "!")
... 
Give me a K!
Give me a y!
Give me a l!
Give me a e!

How for works

So what is going on here?

  1. The for loop looks at what it will iterate through - in this case it is a string, Kyle
  2. We are referring to each element of our string, Kyle, as character.
  3. The loop evaluates the expression passed to the print function for each character in Kyle successively

So the for loop is equivalent to:

print("Give me a K!")
print("Give me a y!")
print("Give me a l!")
print("Give me a e!")

The while loop

  • while repeats an action until a given condition is satisfied
  • Example:
In [1]: i = 5
   ...: 
   ...: while i > 0: 
   ...:     print(str(i) + "...")
   ...:     i = i - 1
   ...: 
   ...: print("Blast-off!")
5...
4...
3...
2...
1...
Blast-off!

How while works

  1. We define a counter, i, that we set to 5 before running the loop
  2. While the value of i is greater than 0, we tell Python to evaluate the print function
  3. With each run of the loop, we subtract 1 from i
  4. When i is equal to 0, we exit the loop and print "Blast-off" to the console

Beware of the infinite while loop!

Conditional logic

  • However - what if we don’t want to do the same thing every time we run a loop? Or a function, for that matter?
  • Answer: conditional logic

Conditional logic

  • Conditional statements in Python: if, elif, and else
  • Conditional operators:
    • < Less than
    • > Greater than
    • <= Less than or equal to
    • >= Greater than or equal to
    • == Is equal to
    • != Is not equal to
  • Booleans: True and False
  • Boolean operators: and, or, & not

Conditional logic in Python

  • Example:
>>> mylist = [2, 4, 6, 8, 10, 12]
>>> for number in mylist: 
...     if number > 7: 
...         print(str(number) + " is greater than 7!")
...     else: 
...         print(str(number) + " is less than 7!")
... 
2 is less than 7!
4 is less than 7!
6 is less than 7!
8 is greater than 7!
10 is greater than 7!
12 is greater than 7!

Conditional logic in functions

  • When writing functions, you’ll rely heavily on conditional statements
def is_even(x): 
    if x % 2 == 0: 
        return(True)
    else: 
        return(False)

>>> is_even(8)
True
>>> is_even(99)
False

Object-oriented programming

  • Programming paradigm in which language is oriented around data objects
  • In Python, “everything is an object!”

Classes

  • A class is a special type of Python object that itself can have attributes and methods
  • Associated with object-oriented programming in Python

How classes work

class Employee:
    company = "TCU"
    
    def __init__(self, name, salary): 
        self.name = name
        self.salary = salary

# Let's create a class instance
doug = Employee(name = "Doug", salary = 50000) 

doug.company

'TCU' # the result

Class attributes and methods

  • Class attributes: attributes that are associated with a given class
    • Attributes can be associated with the class or class instances
  • Class methods: functions associated with the class

def get_raise(self, raise_amount):
    self.salary = self.salary + raise_amount
    
doug.get_raise(5000)